<template>
  <div class="login-box">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="80px" class="demo-ruleForm">
      <h2>后台管理系统</h2>
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button class="loginBtn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button class="loginBtn" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { LoginFormInit } from '@/type/login.js';
import { login } from '../request/api';
import { useRouter } from 'vue-router'
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<LoginFormInit>({
  username: '',
  password: ''
});
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入你的账号', trigger: 'blur' },
    { min: 3, max: 10, message: '账号的长度在3到10之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入你的密码', trigger: 'blur' },
    { min: 3, max: 10, message: '密码的长度在3到10之间', trigger: 'blur' },
  ]
})
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      login(ruleForm).then((res) => {
        // console.log(res);
        localStorage.setItem('token', res.data.token);
        router.push('/');
      })
    } else {
      console.log('error submit!');
      return false;
    }
  })
}
const resetForm = () => {
  ruleForm.username = '';
  ruleForm.password = '';
}
</script>

<style scoped lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  background: url('../assets/bg.jpeg') no-repeat center center / cover;
  overflow: hidden;

  .demo-ruleForm {
    width: 500px;
    margin: 200px auto;
    background-color: #fff;
    padding: 40px;
    border-radius: 20px;
    text-align: center;

    h2 {
      margin-bottom: 20px;
    }

    .loginBtn {
      width: 48%;
    }
  }
}
</style>